package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工控制器
 * 完成登录登出，增删改查
 */
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //请求数据，封装对象里  客户端post请求,要加@RequestBody
    //响应json字符串
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request, HttpServletResponse response) {
        //打印  输出请求参数，便于排错
        log.info("[员工登录] employee: {}", employee);
        //具体业务开发
        //通过service完成业务
        //将客户端密码进行MD5处理
        String password = employee.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据用户名去查询
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //通过wrapper进行查询
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper);
        //如果one不为空
        if (one == null) {
            //如果为空，用户名不正确
            return R.error("用户名不正确");
        }
        //如果one不为空，用户名正确
        if (!one.getPassword().equals(md5Password)) {
            //登陆失败
            return R.error("密码不正确");
        }

        //密码正确看员工状态
        Integer status = one.getStatus();
        if (status == 0) {
            return R.error("登陆失败，员工被禁用");
        }

        //员工ID存入Session
        request.getSession().setAttribute("employee", one.getId());

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        return R.success(one);
    }

    //员工登出操作
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        log.info("[员工登出]");
        request.getSession().removeAttribute("employee");
        return R.success("登出成功");
    }

    //增加保存员工的控制器方法
    //json数据
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //输出请求数据
        log.info("[新增员工],emp:{}", employee);
        //设置密码MD5
        String md5Pass = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(md5Pass);
        //设置创建和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //创建用户创建和更新用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        log.info("[保存数据库之前]:{}", employee);
        //保存用户
//        try {
        employeeService.save(employee);
//        }catch (Exception e){
//            e.printStackTrace();
//            if (e.getMessage().contains("Duplicate entry")){
//                return R.error("数据库发送异常，不允许数据重复");
//            }else {
//                return R.error("数据库位置异常");
//            }
//        }
        return R.success("新增成功");
    }

    //处理分页查询方法
    //返回值Page
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //把请求参数封装到page对象中
        Page pageInfo = new Page(page,pageSize);
        //service获取分页数据
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name)&&!name.equals("null"),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        log.info("[员工查询-分页列表],查询前，page：{}",pageInfo);
        employeeService.page(pageInfo,queryWrapper);
        log.info("[员工查询-分页列表],查询后,page:{}",pageInfo);
        //从数据库查询出来的没有问题， json转换时，精度丢失

        return R.success(pageInfo);
    }

    //修改的方法
    @PutMapping
    public R<String>update(HttpServletRequest request,@RequestBody Employee employee){
        log.info("[员工更新],emp:{}",employee);
        //设置更新时间和更新用户ID
//        employee.setUpdateTime(LocalDateTime.now());
//
//        Long empId = (Long)request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);

        employeeService.updateById(employee);
        return R.success("更新成功");
    }

    //实现根据id做查询
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id) {
        log.info("[基于id查询]，id:{}", id);
        //根据service  查数据
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("无此员工");
    }
}